package edu.lingnan.house.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import edu.lingnan.house.pojo.TbCollection;
import edu.lingnan.house.pojo.TbUser;
import edu.lingnan.house.service.TbCollectionService;
import edu.lingnan.house.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

@RestController
@RequestMapping("lin-collection")
@CrossOrigin
public class CollectionController {
    @Autowired
    private TbCollectionService tbCollectionService;

    @PostMapping("saveCollection")
    public Result Collection(HttpSession session,Integer houseId){
        //获取登陆用户信息
        TbUser tbUser = (TbUser) session.getAttribute("tbUser");

        //判断是否登录
        if(tbUser==null){
            return new Result(202,"请先登录");
        }

        String id = tbUser.getId();

        //插入前先查询此用户关注表判断是否有相同关注信息
        QueryWrapper<TbCollection> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",id).eq("house_id",houseId);
        Integer num = tbCollectionService.count(queryWrapper);
        if(num>=1){
            return new Result(201,"你已关注过该房子");
        }

        //插入房子id和用户id
        TbCollection tbCollection = new TbCollection().setHouseId(houseId).setUserId("134").setCreateTime(LocalDateTime.now());
        Boolean insertCollection = tbCollectionService.save(tbCollection);
        return new Result(200,insertCollection,"ok");

    }

}
